package org.oschina.api.user.role.dao;

import java.util.List;
import org.oschina.Constants;
import org.oschina.api.BaseDAO;
import org.oschina.api.user.bar.dao.UserBarRoleDAO;
import org.oschina.api.user.menu.dao.UserMenuRoleDAO;
import org.oschina.api.user.role.model.UserRoleType;
import org.oschina.api.user.role.vo.UserRoleTypeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class UserRoleTypeDAO extends BaseDAO {

	private final String find[]={"id","name","_default"};
	private final String findVo[]={"id","name","_default"};
	
	@Autowired
	private UserBarRoleDAO userBarRoleDAO;
	@Autowired
	private UserMenuRoleDAO userMeuRoleDAO;
	@Autowired
	private UserRoleDAO userRoleDAO;
	
	/**
	 * 返回用户类型
	 * @return
	 */
	public List<UserRoleTypeVo> findVo()
	{
		return getQueryHelper().query_cache(findVo,null,new String[]{"ORDER BY _default DESC"}, null, UserRoleTypeVo.class, -1, -1);
	}
	
	/**
	 * 返回默认
	 * @return
	 */
	public UserRoleTypeVo getDefault()
	{
		return (UserRoleTypeVo) getQueryHelper().queryForObject_cache(findVo,new String[]{"_default=true"},null,UserRoleTypeVo.class);
	}
	
	/**
	 * 根据ID返回
	 * @param id
	 * @return
	 */
	public UserRoleTypeVo findById(int id)
	{
		return (UserRoleTypeVo) getQueryHelper().queryForObject_cache(findVo, new String[]{"id=?"}, new Object[]{id}, UserRoleTypeVo.class);
	}
	
	/**
	 * 设置默认
	 * @param id
	 * @return
	 */
	public int setDefault(int id)
	{
		getQueryHelper().update("UPDATE "+Constants.DB_USER_ROLE_TYPE+" SET _default=0",null);
		return (int) getQueryHelper().update_cache(new String[]{"_default=1"}, new String[]{"id=?"}, new Object[]{id}, UserRoleTypeVo.class);
	}
	
	/**
	 * 创建
	 * @param roleType
	 * @return
	 */
	public UserRoleType create(UserRoleType roleType)
	{
		getQueryHelper().insert_cache(new String[]{"id","name","_default"}, new Object[]{roleType.getId(),roleType.getName(),roleType.get_default()},UserRoleTypeVo.class);
		return roleType;
	}
	
	/**
	 * 更新
	 * @param roleType
	 * @return
	 */
	public int update(UserRoleType roleType)
	{
		return (int) getQueryHelper().update_cache(new String[]{"name=?"}, new String[]{"id=?"}, new Object[]{roleType.getName(),roleType.getId()},UserRoleTypeVo.class);
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public int delete(int id)
	{
		userBarRoleDAO.removeByRole(id);
		userMeuRoleDAO.removeByRole(id);
		userRoleDAO.removeByRole(id);
		return (int) getQueryHelper().delete_cache(new String[]{"id=?"}, new Object[]{id},UserRoleTypeVo.class);
	}
	
	private String getIdKey(Object id)
	{
		return getKey(Constants.CACHE_USER_ROLE_TYPE,id);
	}
}